<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace buwang\service;

use buwang\facade\WechatMp;
use buwang\util\File;
use GuzzleHttp\Client;
use think\facade\Filesystem;

class UploadService
{
    /**
     * 公众号或者小程序操作对象
     * @var null
     */
    static public $wechatApp=null;
    /**
     * 上传文件
     * @param file $file 文件流
     * @param string $filename input框的name
     * @param string $filepath 存储路径
     * @param string $rule 验证规则
     * @param int $maxsize 允许文件上传的大小 默认为2m
     * @param bool $fileas 是否用原文件名上传保存 默认false
     * @return array
     */
    public static function uploadFile($file, $filename = 'file', $filepath = '', $rule = 'fileExt:jpg,jpeg,png,gif,pem|fileMime:image/jpeg,image/gif,image/png,text/plain', $fileas = false)
    {

        $disk = 'public';
        $maxsize = bw_config('upload_size', 2097152);
        try {


            //文件夹名是当前日期
            //$dir = date("Y") . "/" . date("m") . "/" . date("d");
            $dir = 'upload';
            if ($file->getSize() > $maxsize) {
                throw new \Exception('上传失败,文件超出大小,请选择' . floor($maxsize / 1024 / 1024) . 'm以内的文件');
            }
//            validate([$filename => $rule])->check([$filename => $file]);

            $validate = \think\facade\Validate::rule([$filename => $rule]);
            if (!$validate->check([$filename => $file])) {
                throw new \Exception($validate->getError());
            }

            //上传的地址
            if ($filepath) {
                $savename = $fileas == false ? Filesystem::disk($disk)->putFile($filepath, $file) : Filesystem::disk($disk)->putFileAs($filepath . '/' . date('Ymd'), $file, $file->getOriginalName());
            } else {
                // var_dump($dir);die;
                $savename = $fileas == false ? Filesystem::disk($disk)->putFile($dir, $file) : Filesystem::disk($disk)->putFileAs($dir, $file, $file->getOriginalName());
            }
            $path_config = Filesystem::getDiskConfig($disk);
            $save_url = $path_config['root'].$path_config['url'].$savename;
            // return self::rMsg(0, '上传成功', Filesystem::getDiskConfig($disk, 'url') . '/' . str_replace('\\', '/', $savename), $file->getOriginalName());
            return [
                'src' => request()->domain() . '/' .Filesystem::getDiskConfig($disk, 'url') . '/'  . str_replace('\\', '/', $savename),
                'path'=>$save_url,
                'original_name' => $file->getOriginalName(),
            ];

        } catch (ValidateException $e) {
            throw new \Exception($e->getMessage());
        }


    }

    /**
     * 上传临时素材
     * @param $url
     * @param string $type
     * @param array $data
     */
    public static function uploadMedia($url,$type ='image',$is_miniapp = false,$member_miniapp_id ='',$app_id='', $upload_type = 'media',$data=[])
    {
        if (!in_array($type, ['image', 'voice', 'video', 'thumb'])) {
            return self::error('上传素材类型错误！');
        }
        //上传图片到微信服务器,并返回mediaId
        $upload_set_type = bw_config('base')['upload_type'];
        $thumb_img = substr(parse_url($url)['path'],1);
        //进行存储media资源到表WechatMedia
        //$where = ['md5' => md5($url), 'appid' => $this->app_id];
        $where[] = ['md5', '=', md5($url)];
        $where[] = ['appid', '=', $app_id];
        if($is_miniapp) $where[] = ['create_at', '>', time()-86400*3-3600];//小程序临时素材只能保存3天

        //查询如果存在就直接返回
        if (($mediaId = app()->db->name('WechatMedia')->where($where)->value('media_id'))) return ['code'=>0,'msg'=>'success','media_id'=>$mediaId];
        //获取公众号或者小程序操作对象
        self::$wechatApp = WechatMp::getWechatObj($member_miniapp_id);
        if(true){
            if($upload_set_type != 'local'){//如果是远程存储下载到本地再上传
                $thumb_path = root_path('public').$thumb_img;

                if (!file_exists($thumb_path)) {//如果本地下载过这个文件就不再下载
                    if(File::mk_dir(dirname($thumb_path))){
                        //下载文件START
                        try{
                            $client = new Client(['verify'=>false]);
                            $client->get($url,['save_to'=>$thumb_path]);
                        }catch(\Exception $e){
                            return self::error("下载文件失败：".$e->getMessage());
                        }
                        //下载文件END
                    }
                }
            }else{//如果是本地存储模式
                $thumb_path = root_path('public').$thumb_img;
            }

            if(file_exists($thumb_path)){
                try {
                    if($is_miniapp){
                        //图片（image）: 2M，支持 JPG 格式
                        $thumb = self::$wechatApp->media->uploadImage($thumb_path);
                    }else{
                        switch ($type){
                            case 'image':
                                $thumb = self::$wechatApp->material->uploadImage($thumb_path);
                                break;
                            case 'video':
                                $thumb = self::$wechatApp->media->uploadVideo($thumb_path, $data['title'], $data['desc']);
                                break;
                            case 'voice':
                                $thumb = self::$wechatApp->media->uploadVoice($thumb_path);
                                break;
                        }
                    }
                }catch (\Exception $e){
                    return self::error("上传失败:".$e->getMessage());
                }


                if(empty($thumb['media_id'])){
                    return self::error("上传资源到微信服务器失败,类型为：".$type);
                }
                $result['media_id'] = $thumb['media_id'];
                $result['media'] = json_encode($thumb);
            }
        }
        $mediaData =[
            'local_url' => $url, 'md5' => $where['md5'], 'appid' => $where['appid'], 'type' => $type,
            'media_url' => isset($thumb['url']) ? $thumb['url'] : '', 'media_id' => $result['media_id'],
            'media'     =>  $result['media'],'creat_at'=> time()
        ];
        try {
            if (($info = app()->db->name('WechatMedia')->where($where)->find()) && !empty($info)) {
                app()->db->name('WechatMedia')->strict(false)->where($where)->update($mediaData);
            } else {
                app()->db->name('WechatMedia')->strict(false)->insertGetId($mediaData);
            }
        }catch (\Exception $e){
            return self::error("更新wechatMedia数据失败:".$e->getMessage());
        }
        return ['code'=>0,'msg'=>'success','media_id'=>$result['media_id']];
    }


    /**
     * 返回值处理
     * @param string $msg
     * @param int $err_code
     * @param string $media_id
     * @return array
     */
    private function error($msg='',$err_code =4000000,$media_id=''){

        return [
            'code'  =>$err_code,
            'msg'=>$msg,
            'media_id'=>$media_id
        ];
    }


}